#!/bin/bash

echo "=== 黑马商城Docker集群部署脚本 ==="

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo "错误: Docker未安装，请先安装Docker"
    exit 1
fi

# 检查Docker Compose是否安装
if ! command -v docker-compose &> /dev/null; then
    echo "错误: Docker Compose未安装，请先安装Docker Compose"
    exit 1
fi

echo "✓ Docker环境检查通过"

# 创建必要的目录
echo "创建必要的目录..."
mkdir -p mysql/conf mysql/init logs

# 停止并删除现有容器
echo "清理现有容器..."
docker-compose down -v

# 构建并启动MySQL
echo "开始部署MySQL数据库..."
docker-compose up -d mysql

echo "等待MySQL启动..."
sleep 30

# 检查MySQL是否启动成功
echo "检查MySQL状态..."
if docker-compose ps mysql | grep -q "Up"; then
    echo "✓ MySQL启动成功"
else
    echo "✗ MySQL启动失败，请检查日志"
    docker-compose logs mysql
    exit 1
fi

# 初始化数据库
echo "初始化数据库..."
docker-compose exec mysql mysql -uroot -proot -e "source /docker-entrypoint-initdb.d/01-init-databases.sql"

echo "✓ MySQL部署完成！"
echo ""
echo "=== 部署信息 ==="
echo "MySQL端口: 3306"
echo "MySQL用户名: root"
echo "MySQL密码: root"
echo "数据库列表:"
echo "  - hmall (主数据库)"
echo "  - hm-user (用户服务)"
echo "  - hm-item (商品服务)"
echo "  - hm-cart (购物车服务)"
echo "  - hm-trade (交易服务)"
echo "  - hm-pay (支付服务)"
echo "  - nacos_config (Nacos配置)"
echo ""
echo "连接MySQL:"
echo "  docker exec -it hmall-mysql mysql -uroot -proot"
echo ""
echo "查看MySQL日志:"
echo "  docker-compose logs mysql"
echo ""
echo "下一步: 运行 ./deploy-full.sh 部署完整集群" 